package tools;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;

import biblioteque.Bibliotheque;
import biblioteque.Mot;

public class unlimitedHashMap implements Serializable {
	
	private Vector<HashMap< String,Mot> > myHashMaps;
	public static int NB_MAX_VALUE=40000;
	
	public unlimitedHashMap()
	{
		myHashMaps = new Vector<HashMap< String,Mot> >();
	}
	
	public Mot get(String key)
	{
long t1= System.currentTimeMillis();
		
	
	
		boolean found = false;
		int cpt = 0;
		Mot value=null;
		
		while(!found && cpt<myHashMaps.size() )
		{
			if(myHashMaps.get(cpt).containsKey(key))
			{
				value = myHashMaps.get(cpt).get(key);
				found = true;
			}
			cpt++;
		}
		
long t2= System.currentTimeMillis();
		
		//System.out.println("Trouve en " + String.valueOf(t1)+ " " +String.valueOf(t2));
	
		return value;
		
		
	}
	
	public boolean containsKey(String key)
	{
		return (this.get(key)!= null);
	}
	
	
	public HashMap<String, Mot> getHashMap(String key)
	{
		HashMap<String, Mot> hm = null;
		boolean found = false;
		int cpt = 0;
	
		while(!found && cpt < myHashMaps.size() )
		{
	
			if((myHashMaps.get(cpt)).containsKey(key))
			{		
				hm = myHashMaps.get(cpt);
				found = true;
			}
			cpt++;
		}

		return hm;
	}
	
	public void put(String key, Mot value)
	{
		
		long t1= System.currentTimeMillis();
		
		
		HashMap<String, Mot> hm = this.getHashMap(key);
		
		if(hm==null && this.myHashMaps.size()==0)
		{

			HashMap<String,Mot> hmSup = new HashMap<String,Mot>(); 
			hmSup.put(key, value);
			this.myHashMaps.add(hmSup);
		}
		
		
		//Si pas trouve
		if(hm==null)
		{
			//On lajoute a la derniere hashMap
			//on verifie dabord la taille de la derniere
			if(this.myHashMaps.lastElement().size() <= NB_MAX_VALUE  ) 
				this.myHashMaps.lastElement().put(key, value);
			else
			{
				HashMap<String,Mot> hmSup = new HashMap<String,Mot>(); 
				hmSup.put(key, value);
				this.myHashMaps.add(hmSup);
				System.out.println("---------------------------------");
				System.out.println("AJOUT DUNE HASHMAP - " + this.myHashMaps.size());
				System.out.println("---------------------------------");
			}
			
		}
		else 
		{
			this.myHashMaps.lastElement().put(key, value);
			
		}
		
long t2= System.currentTimeMillis();
		
		//System.out.println("Ajoute en " + String.valueOf((t2-t1)));
	}
	
	public ArrayList<Set<Entry<String,Mot>>> entrySet()
	{
		ArrayList<Set<Entry<String,Mot>>> listMots = new ArrayList<Set<Entry<String,Mot>>>();
		
		for(HashMap< String,Mot> hm : this.myHashMaps )
		{
			listMots.add(hm.entrySet());
		}
		
		return listMots;
	}
}
